package com.dream.jump.data

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import javax.inject.Inject

val Context.settingsDataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

@Module
@InstallIn(SingletonComponent::class)
class DataStoreClient @Inject constructor(@ApplicationContext private val context: Context) {
    companion object {
        val UserNameKey = stringPreferencesKey("userName")
        val PasswordKey = stringPreferencesKey("password")
        val AccessTokenKey = stringPreferencesKey("accessToken")
    }

    /**
     * 保存数据
     * */
    suspend fun putDataStore(mapValue: Map<Preferences.Key<String>, String>) {
        context.settingsDataStore.edit { setting ->
            mapValue.forEach { (key, value) -> setting[key] = value }
        }
    }

    /**
     * 获取数据
     * */
    suspend fun getValueByKey(key: Preferences.Key<String>): String {
        val nameFlow: Flow<String> = context.settingsDataStore.data.map { settings ->
            settings[key] ?: ""
        }
        return nameFlow.first()
    }

}

